package com.hzgj.bcl.soa;

import com.google.common.collect.Maps;
import com.hzgj.bcl.soa.command.CommandsInitializer;
import com.hzgj.bcl.soa.controller.logic.PageLogic;
import com.hzgj.bcl.soa.util.ServiceLoaderUtil;
import com.hzgj.bcl.util.IocContext;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by Administrator on 2016/9/5.
 */
@Component
public class CliLoader implements ApplicationContextAware {

    private Map<String, PageLogic> pageLogicMap;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        IocContext.applicationContext = applicationContext;
        CommandsInitializer.load();
    }

    @PostConstruct
    public void loadPageLogic() {
        Iterator<PageLogic> iterator = ServiceLoaderUtil.getServiceLoaderObjects(PageLogic.class);
        if (iterator != null) {
            pageLogicMap = Maps.newHashMap();
        }
        iterator.forEachRemaining(pageLogic -> {
            if (pageLogic.getPages() != null) {
                pageLogic.getPages().forEach(page -> {
                    pageLogicMap.putIfAbsent(page, pageLogic);
                });
            }
        });
    }

    public PageLogic getPageLogic(String name) {
        return pageLogicMap.get(name);
    }
}
